package admin

import (
	"APT/api/admin/pms"
	"APT/internal/dao"
	"APT/internal/library/airhousePublicApi"
	"APT/internal/library/contexts"
	"APT/internal/model/entity"
	"APT/internal/model/input/input_refund"
	"APT/internal/service"
	"context"
	"database/sql"
	"errors"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

func (c *ControllerPms) RefundOrder(ctx context.Context, req *pms.RefundOrderReq) (res *pms.RefundOrderRes, err error) {
	var (
		RoomReservation []*entity.PmsAppReservation
		PmsTransaction  []*entity.PmsTransaction
	)
	if err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		if req.IsCancelOrder == "Y" {
			if err = dao.PmsTransaction.Ctx(ctx).TX(tx).Where(dao.PmsTransaction.Columns().OrderSn, req.OrderSn).Scan(&PmsTransaction); err != nil {
				return
			}
			for _, PmsTransactionItem := range PmsTransaction {
				if PmsTransactionItem.RefundStatus != "DONE" && PmsTransactionItem.PayType != "COUPON" {
					err = gerror.New("已退款，是部分退款无法进行取消订单")
					return
				}
			}
			// 查询入住订单信息 进行取消操作
			if err = dao.PmsAppReservation.Ctx(ctx).TX(tx).Where(g.MapStrAny{
				dao.PmsAppReservation.Columns().OrderSn: req.OrderSn,
				//dao.PmsAppReservation.Columns().Id:      req.Id,
			}).Scan(&RoomReservation); err != nil {
				return
			}
			if g.IsEmpty(RoomReservation) {
				err = gerror.New("不存在入住单")
				return
			}

			for _, RoomReservationItem := range RoomReservation {
				if RoomReservationItem.Status != "confirmed" {
					err = gerror.New("已退款，订单不是确认状态，无法取消")
					return
				}
				if _, err = airhousePublicApi.UpdateRoomReservationPost(ctx, RoomReservationItem.Uuid, g.MapStrAny{
					"status":           "cancelled",
					"checkin_date":     RoomReservationItem.CheckinDate,
					"checkout_date":    RoomReservationItem.CheckoutDate,
					"cancellation_fee": RoomReservationItem.BookingFee,
					"booking_fee":      0,
				}); err != nil {
					return
				}
				// 更新入住订单信息
				if _, err = dao.PmsAppReservation.Ctx(ctx).TX(tx).Where(dao.PmsAppReservation.Columns().Uuid, RoomReservationItem.Uuid).Data(g.MapStrAny{
					dao.PmsAppReservation.Columns().OrderStatus:     "CANCEL",
					dao.PmsAppReservation.Columns().Status:          "cancelled",
					dao.PmsAppReservation.Columns().CancellationFee: 0,
					dao.PmsAppReservation.Columns().CancelRemake:    "退款取消:" + req.Reason,
				}).Update(); err != nil {
					return
				}
			}
		}
		err = service.Refund().RefundOrder(ctx, &input_refund.RefundAmountInp{
			OrderSn:      req.OrderSn,
			RefundAmount: req.RefundAmount,
		}, tx)
		return
	}); err != nil {
		return
	}
	// 修改主订单为已取消
	if _, err = dao.PmsAppStay.Ctx(ctx).Where(dao.PmsAppStay.Columns().OrderSn, req.OrderSn).Data(g.MapStrAny{
		dao.PmsAppReservation.Columns().OrderStatus: "CANCEL",
	}).Update(); err != nil {
		return
	}

	// 酒店订单退款
	var (
		PmsAppStay entity.PmsAppStay
	)
	if err = dao.PmsAppStay.Ctx(ctx).Where(g.MapStrAny{
		dao.PmsAppStay.Columns().OrderSn: req.OrderSn,
	}).Scan(&PmsAppStay); err != nil && errors.Is(err, sql.ErrNoRows) {
		return
	}
	if g.IsEmpty(PmsAppStay) {
		err = gerror.New("该订单无需处理")
		return
	}
	if _, err = dao.PmsAppStayLog.Ctx(ctx).OmitEmptyData().Insert(&entity.PmsAppStayLog{
		OrderId:     PmsAppStay.Id,
		ActionWay:   "REFUND",
		Remark:      "订单退款",
		OperateType: "ADMIN",
		OperateId:   int(contexts.GetUserId(ctx)),
	}); err != nil {
		return
	}
	return
}
